import { createRouter, createWebHistory } from "vue-router";
// 在路由配置中使用
import { mockMenuData } from "@/mock/menuData";
import { buildMenuTree, generateRoutes } from "@/utils/routeGenerator";

// 生成路由配置
const menuTree = buildMenuTree(
  JSON.parse(localStorage.getItem("menuList") || "[]")
);
const dynamicRoutes = generateRoutes(menuTree);

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/404",
      component: () => import("@/views/error/404.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/403",
      component: () => import("@/views/error/403.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/login",
      component: () => import("@/views/LoginView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/",
      component: () => import("@/layouts/MainLayout.vue"),
      meta: { requiresAuth: true },
      children: [
        {
          path: "/home",
          name: "Home",
          meta: {
            title: "主页",
            icon: "House",
            affix: true,
            hidden: false,
            alwaysShow: false,
          },
          children: [],
        },
        ...dynamicRoutes,
      ],
    },
  ],
});

router.beforeEach((to, from, next) => {
  const publicPages = ["/login", "/404"];
  const authRequired = !publicPages.includes(to.path);
  const userId = localStorage.getItem("userId");

  // 处理未匹配路由
  if (to.matched.length === 0) {
    next("/404");
    return;
  }

  if (authRequired && !userId) {
    // 携带原始路径作为查询参数
    next({
      path: "/login",
      query: { redirect: to.fullPath }, // 保留完整路径（包含查询参数）
    });
  } else {
    next();
  }
});

export default router;
